import { MotionPlugin } from "@vueuse/motion";
import { createPinia } from "pinia";
import { createApp } from "vue";
import VueTippy from "vue-tippy";
import { useReCommon } from "@/components/ReCommon";
import { tokenStorage } from "@/config/storage";
import { setupDirectives } from "@/directives";
import useElementPlus from "@/plugins/elementPlus";
import { i18n } from "@/plugins/i18n";
import { initRouter } from "@/router/utils";
import { ok as okFn, okPage as okPageFn } from "@/utils/http/resp-guard";
import App from "./App.vue";
import { setPlatformConfigs } from "./config";
import router from "./router";
import "tippy.js/dist/tippy.css"; // 需要安装tippy.js
import "@/style/reset.scss"; // 重置样式
import "@/style/index.scss"; // 全局样式
import "@/style/tailwind.css"; // tailwind样式
import "element-plus/dist/index.css";

// 绑定全局函数, 同时在 types/global.d.ts 中声明类型
(window as any).ok = okFn;
(window as any).okPage = okPageFn;

const app = createApp(App);

app.use(createPinia());
setPlatformConfigs(app).then(async () => {
    console.info("全局配置加载完成...");

    try {
        // 如果存在 token，先初始化后端动态路由，避免刷新时路由尚未加载导致 No match found 错误
        if (tokenStorage.value?.accessToken) {
            await initRouter();
        }
    } catch (err) {
        console.error("initRouter 初始化失败:", err);
    }

    app.use(router);
    app.use(useElementPlus);
    app.use(useReCommon);
    app.use(MotionPlugin);
    app.use(i18n);
    app.use(VueTippy, {}); // 全局注册vue-tippy
    setupDirectives(app); // 注册自定义指令
    app.mount("#app");
});
